// API服务配置
const API_BASE_URL = 'http://localhost:8081/api';

// 缓存配置
const CACHE_CONFIG = {
  enabled: true,
  defaultTTL: 30000, // 30秒缓存
  cacheableMethods: ['GET'],
};

// 请求去重管理器
class RequestDeduplicator {
  constructor() {
    this.activeRequests = new Map();
  }

  getRequestKey(endpoint, options) {
    return `${endpoint}_${options.method || 'GET'}_${JSON.stringify(options.body || {})}`;
  }

  async getCachedOrCreate(endpoint, options, fetchFn) {
    const key = this.getRequestKey(endpoint, options);
    
    // 如果有相同请求正在进行，返回现有Promise
    if (this.activeRequests.has(key)) {
      return this.activeRequests.get(key);
    }

    // 创建新请求
    const requestPromise = fetchFn().finally(() => {
      // 请求完成后从活跃请求中移除
      this.activeRequests.delete(key);
    });

    // 存储活跃请求
    this.activeRequests.set(key, requestPromise);
    return requestPromise;
  }
}

// 缓存管理器
class CacheManager {
  constructor() {
    this.cache = new Map();
  }

  getKey(endpoint, options) {
    return `${options.method || 'GET'}_${endpoint}_${JSON.stringify(options.body || {})}`;
  }

  get(key) {
    const cached = this.cache.get(key);
    if (cached && Date.now() < cached.expiry) {
      return cached.data;
    }
    // 缓存过期，删除
    if (cached) {
      this.cache.delete(key);
    }
    return null;
  }

  set(key, data, ttl = CACHE_CONFIG.defaultTTL) {
    this.cache.set(key, {
      data,
      expiry: Date.now() + ttl,
    });
  }

  clear() {
    this.cache.clear();
  }
}

// 创建单例实例
const cacheManager = new CacheManager();
const requestDeduplicator = new RequestDeduplicator();

// 通用HTTP请求方法
class ApiService {
  constructor() {
    this.token = localStorage.getItem('auth_token');
    this.timeout = 10000; // 10秒超时
  }

  setToken(token) {
    this.token = token;
    if (token) {
      localStorage.setItem('auth_token', token);
    } else {
      localStorage.removeItem('auth_token');
    }
    // 清除缓存，确保认证状态变更后获取最新数据
    cacheManager.clear();
  }

  getHeaders() {
    const headers = {
      'Content-Type': 'application/json',
    };
    
    if (this.token) {
      headers['Authorization'] = `Bearer ${this.token}`;
    }
    
    return headers;
  }

  // 添加超时处理的fetch包装
  async fetchWithTimeout(url, options) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), this.timeout);

    try {
      const response = await fetch(url, {
        ...options,
        signal: controller.signal,
      });
      clearTimeout(timeoutId);
      return response;
    } catch (error) {
      clearTimeout(timeoutId);
      if (error.name === 'AbortError') {
        throw new Error('请求超时，请稍后重试');
      }
      throw error;
    }
  }

  // 重试逻辑
  async fetchWithRetry(url, options, retries = 2, delay = 1000) {
    try {
      return await this.fetchWithTimeout(url, options);
    } catch (error) {
      // 只对网络错误和超时错误进行重试
      if (retries > 0 && (error.name === 'AbortError' || !error.response)) {
        await new Promise(resolve => setTimeout(resolve, delay));
        return this.fetchWithRetry(url, options, retries - 1, delay * 2); // 指数退避
      }
      throw error;
    }
  }

  async request(endpoint, options = {}) {
    const url = `${API_BASE_URL}${endpoint}`;
    const requestOptions = {
      ...options,
      headers: {
        ...this.getHeaders(),
        ...options.headers,
      },
    };

    // 检查是否可缓存
    const isCacheable = CACHE_CONFIG.enabled && 
                       CACHE_CONFIG.cacheableMethods.includes(options.method || 'GET');

    if (isCacheable) {
      const cacheKey = cacheManager.getKey(endpoint, requestOptions);
      const cachedData = cacheManager.get(cacheKey);
      if (cachedData) {
        return cachedData;
      }
    }

    // 使用请求去重
    try {
      const response = await requestDeduplicator.getCachedOrCreate(
        endpoint,
        requestOptions,
        async () => {
          return await this.fetchWithRetry(url, requestOptions);
        }
      );

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || `请求失败: ${response.status}`);
      }

      const data = await response.json();

      // 缓存结果
      if (isCacheable) {
        const cacheKey = cacheManager.getKey(endpoint, requestOptions);
        cacheManager.set(cacheKey, data);
      }

      return data;
    } catch (error) {
      // 减少错误日志输出，避免性能影响
      console.error('API请求错误:', error.message);
      throw error;
    }
  }

  get(endpoint) {
    return this.request(endpoint, {
      method: 'GET',
    });
  }

  post(endpoint, data) {
    return this.request(endpoint, {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  put(endpoint, data) {
    return this.request(endpoint, {
      method: 'PUT',
      body: JSON.stringify(data),
    });
  }

  delete(endpoint) {
    return this.request(endpoint, {
      method: 'DELETE',
    });
  }
}

// 认证相关API
export const authService = {
  async login(username, password) {
    const api = new ApiService();
    const response = await api.post('/auth/signin', { username, password });
    api.setToken(response.token);
    return response;
  },

  async register(username, email, password, fullName) {
    const api = new ApiService();
    return await api.post('/auth/signup', { username, email, password, fullName });
  },

  logout() {
    const api = new ApiService();
    api.setToken(null);
  },

  isAuthenticated() {
    return !!localStorage.getItem('auth_token');
  },
};

// 产品相关API
export const productService = {
  async getProducts() {
    const api = new ApiService();
    return await api.get('/products');
  },

  async getPublicProducts() {
    const api = new ApiService();
    return await api.get('/products/public');
  },

  async getProductById(id) {
    const api = new ApiService();
    return await api.get(`/products/${id}`);
  },

  async createProduct(productData) {
    const api = new ApiService();
    return await api.post('/products', productData);
  },

  async updateProduct(id, productData) {
    const api = new ApiService();
    return await api.put(`/products/${id}`, productData);
  },

  async deleteProduct(id) {
    const api = new ApiService();
    return await api.delete(`/products/${id}`);
  },
};

// 导出默认API实例
export default new ApiService();